/**
 * UploadFileUtils.java
 *
 *
 * $LastChangedBy: allen $
 * $LastChangedDate: 2007-12-03 12:17:25 +0800 $
 * $Revision: 1323 $
 */
package com.myspace.view.common;

import java.util.Random;

import org.apache.commons.lang.StringUtils;


/**
 * The tools for upload file.
 *
 * @author Allen.Chen
 *
 */
public class UploadFileUtils {

	public static final int DEFAULT_DEPATH_PATH = 2;

	/**
	 * Build hashed file name.
	 *
	 * @param fileName
	 *            the name of file.
	 * @return the hashed file name.
	 */
	public static String buildHashedFileName(String fileName) {
		if (StringUtils.isEmpty(fileName)) {
			throw new IllegalArgumentException(" File name is empty! ");
		}
		String extName = "";
		int pos = fileName.lastIndexOf(".");
		if (pos > 0 && pos < fileName.length() - 1) {
			extName = fileName.substring(pos + 1, fileName.length());
		}
		String hashName = Long.toHexString(Math.abs(fileName.hashCode()))
				+ Long.toHexString(System.currentTimeMillis()
						+ (new Random().nextInt()));
		if (extName.trim().length() > 0) {
			hashName += "." + extName;
		}
		return hashName;
	}

	/**
	 * Build hashed path url ,the result would be like
	 * "photo/1/3/13AEF2488E.jpg".
	 *
	 * @param fileName
	 *            the hashed file name.
	 * @param path
	 *            the start path
	 * @param pathDepth
	 *            the depth of path.
	 * @return the hashed url path.
	 */
	public static String buildHashedPathURL(String fileName, String path,
			int pathDepth) {
		if (StringUtils.isEmpty(fileName)) {
			throw new IllegalArgumentException("File name is empty!");
		}
		StringBuffer buffer = new StringBuffer();
		buffer.append(path).append(Constant.URL_SEPARATOR);
		int depth = fileName.length() < pathDepth ? fileName.length()
				: pathDepth;
		for (int i = 0; i < depth; i++) {
			buffer.append(fileName.charAt(i)).append(Constant.URL_SEPARATOR);
		}
		buffer.append(fileName);
		return buffer.toString();
	}

	/**
	 * Uses default depth of path to build hashed path url.
	 *
	 * @param fileName
	 *            the hashed file name.
	 * @param path
	 *            the start path
	 * @return the hashed url path.
	 */
	public static String buildHashedPathURL(String fileName, String path) {
		return buildHashedPathURL(fileName, path, DEFAULT_DEPATH_PATH);
	}

}
